import json
import time
import pika
from logger import logger

env_config = json.load(open('env.config.json', 'r'))
mqhost = env_config['rabbitmq_host']

class MsgManager:

    def __init__(self, queue_name):
        self.queue_name = queue_name
        # 连接到RabbitMQ服务器
        connection = pika.BlockingConnection(pika.ConnectionParameters(mqhost))
        channel = connection.channel()
        self.channel = channel
        self.connection = connection

    def send_msg(self, message):

        if self.connection.is_closed:
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(mqhost))
            self.channel = self.connection.channel()
        
        # 发送消息
        self.channel.basic_publish(exchange='',
                                routing_key=self.queue_name,
                                body=message,
                                properties=pika.BasicProperties(
                                delivery_mode=2,  # 使消息持久化
                                ))
        logger.debug(f" [x] Sent {self.queue_name} - '{message}'")

    def msgs(self):
        # 声明一个队列，用于接收消息
        self.channel.queue_declare(queue=self.queue_name, durable=True)

        # 开始接收消息  logger.debug(' [*] Waiting for messages. To exit press CTRL+C')
        # 开始接收消息并产生（yield）它们
        while True:
                method_frame, header_frame, body = self.channel.basic_get(queue=self.queue_name, auto_ack=True)
                if method_frame:
                    yield method_frame.delivery_tag, body.decode()
                else:
                    # 没有消息，暂时休眠避免密集轮询
                    time.sleep(2)  # 可以根据实际情况调整休眠时间
                    logger.debug('[mq] no-msg')

    def close(self):
        self.connection.close()


def clear_msgs(queue_name):
    logger.debug(f" [x] Clearing {queue_name} messages...")
    msg_manager = MsgManager(queue_name)
    for delivery_tag, body in msg_manager.msgs():
        logger.debug(f" [x] Received {delivery_tag} {body}")


def test_send_msg(queue_name):
    msg_manager = MsgManager(queue_name)
    import sys
    msg = sys.argv[1]
    if not msg:
        logger.debug('Please input message to send.')
        exit(1)
    msg_manager.send_msg(msg)


if __name__ == '__main__':
   queue_name = 'wx_msgs_queue'
   test_send_msg(queue_name)

   clear_msgs(queue_name)
